import {
  Router
} from "../../utils/common.js";
const db = wx.cloud.database();
const progWidth = 450
Page({
  data: {
    pet: {},
    pics: [],
    isCollect: 0,
    picLiker: 0,
    picLikeCount: 0,
    isShowCollect: false,
    progWidth,
    progInWidth: 0,
    // levelUp: 10000,
    petId: '', // 宠物ID
    // 分页获取遛狗榜
    feeds: [],
    page: 1,
    totalCount: 0, //数据总数
    userInfo: {}, //用户信息
    petUserInfo: {}, // 宠物主人信息
    showMoreInfo: true, // 分页查询
    number: -1,
    showCard: false
  },
  randomNum(minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        //或者 Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
        break;
      default:
        return 0;
        break;
    }
  },
  translate() {
    let randomNum = this.randomNum(-30, 30)
    // number是控制active的
    this.setData({
      number: this.data.number + 1
    }, () => {
      if (this.data.number > 7) {
        this.setData({
          number: -1
        })
        this.translate();
      }
    })
    // .active 是选择器
    this.animate('.active', [{
      opacity: 1,
      translateY: 0
    },
    {
      opacity: 0,
      translate: [randomNum, -200]
    },
    ], 1000, function () {
      //动画完成后的回调函数
    }.bind(this))
  },
  onLoad: function (options) {
    this.setData({
      petId: options.petId
    })
    // 获取宠物信息
    this.loadPetDet();
    // 获取遛狗达人榜
    this.getFeedList();
    // 判断是否收藏
    this.isCollectPet();
    // 获取狗狗写真集
    this.getPetPics();
    this.getTotalCount(); //获取总数
    // 获取用户信息
    this.getUserInfo();
  },
  /**
   * 获取用户信息
   */
  getUserInfo() {
    db.collection('p_user').where({
      _openid: wx.getStorageSync("openid")
    }).get({
      success: res => {
        if (res.data.length > 0) {
          this.setData({
            userInfo: res.data[0]
          })
        } else { }
      },
      fail: err => {
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },
  loadPetDet() {
    db.collection('p_pets').where({
      _id: this.data.petId
    }).get({
      success: res => {
        let info = res.data[0];
        let isShowCollect = true;
        if (info._openid == wx.getStorageSync('openid')) {
          isShowCollect = false
        }
        this.setData({
          pet: info,
          isShowCollect: isShowCollect
        });
        this.treatmentVelocity();
        // 获取宠物主人信息
        this.getPetUserInfo(info._openid);
      },
      fail: err => {
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },
  /**
   * 处理汪星人运动量以及等级   
   */
  treatmentVelocity() {
    let nextLevelNeed = (this.data.pet.levelNo + 1) * 10000;
    let tmpWidth = this.data.pet.totalEnergy / nextLevelNeed * progWidth
    this.setData({
      progInWidth: tmpWidth
    })
  },
  /**
   * 获取遛狗榜
   */
  getFeedList() {
    db.collection('p_user').orderBy('totalStep', 'desc').skip(0)
      .limit(10)
      .get({
        success: res => {
          this.setData({
            feeds: res.data
          })
        },
        fail: err => {
          console.log('[数据库] [查询记录] 失败：');
        }
      })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  getList: function () {
    let page = this.data.page;
    if (this.data.feeds.length < this.data.totalCount) {
      db.collection('p_user').orderBy('totalStep', 'desc').skip(page * 10)
        .limit(10)
        .get({
          success: res => {
            let feeds = this.data.feeds;
            for (let i = 0; i < res.data.length; i++) {
              feeds.push(res.data[i]);
            }
            this.setData({
              feeds: feeds,
              page: page + 1
            })
          },
          fail: err => {
            console.log('[数据库] [查询记录] 失败：');
          }
        })

    } else if (this.data.showMoreInfo) {
      this.setData({
        showMoreInfo: false
      })
      wx.showToast({
        title: '没有更多数据了',
      })
    }

  },
  /**
   * 获取总数
   */
  getTotalCount() {
    let that = this;
    db.collection('p_user').count({
      success: function (res) {
        console.log(res.total);
        that.setData({
          totalCount: res.total
        })
      }
    })
  },
  /**
   * 是否收入狗圈
   */
  isCollectPet() {
    db.collection('p_pet_collect').where({
      petId: this.data.petId,
      openId: wx.getStorageSync("openid")
    }).get({
      success: res => {
        if (res.data.length > 0) {
          this.setData({
            isCollect: 1,
            pet_collect_id: res.data[0]._id
          })
        }
      },
      fail: err => {
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },
  /**
   * 收藏宠物
   */
  collectPet() {
    let that = this;
    if (that.data.isCollect == 1) {
      // 取消收藏
      db.collection('p_pet_collect').doc(that.data.pet_collect_id).remove({
        success: function () {
          that.setData({
            isCollect: 0
          })
        },
        fail: function () { }
      })
    } else {
      // 收藏
      var collect = {
        petId: this.data.petId,
        openId: wx.getStorageSync("openid"),
      }
      db.collection('p_pet_collect').add({
        data: collect
      }).then(() => {
        this.isCollectPet();
      })
    }
  },
  /**
   * 获取狗狗写真集
   */
  getPetPics() {
    db.collection('p_pet_pics').where({
      petId: this.data.petId,
      activeFlag: 1
    }).limit(6).get({
      success: res => {
        this.setData({
          pics: res.data
        })
      },
      fail: err => {
        this.setData({
          pics: []
        })
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },
  /**
   * 查看狗狗写真集
   */
  navToPetPic: function () {
    let that = this
    let params = {
      petId: that.data.petId
    }
    Router.navigateTo("../dogpic/dogpic", params);
  },
  /**
   * 查看用户宠物列表
   */
  navToSomeonePet: function (e) {
    let openid = e.currentTarget.dataset.openid
    if (openid == wx.getStorageSync("openid")) {
      wx.switchTab({
        url: "/pages/index/index"
      })
    } else {
      let params = {
        openid: openid
      }
      Router.navigateTo("../doglist/doglist", params)
    }

  },
  navToMyPet: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  navToPetEdit: function () {
    let that = this
    let petVali = {
      petNameOk: true,
      sexOk: true,
      birthdayOk: true,
      weightOk: true,
      featureOk: true,
      neuOk: true,
      avatarOk: true,
      breedOk: true
    }
    that.data.pet.avatarTmp = that.data.pet.avatar
    let params = {
      pet: JSON.stringify(that.data.pet),
      petVali: JSON.stringify(petVali)
    }
    Router.navigateTo("../dogedit/dogedit", params);
  },
  /**
   * 获取宠物主人信息
   */
  getPetUserInfo(_openid) {
    db.collection('p_user').where({
      _openid: _openid
    }).get({
      success: res => {
        this.setData({
          petUserInfo: res.data[0]
        });
      },
      fail: err => {
        console.log('[数据库] [查询记录] 失败：');
      }
    })
  },
  /**
   * 遛狗  每次默认减少2000步数 不足2000扣除剩余步数
   */
  feedPet() {
    this.setData({
      showCard: true
    })
    this.translate();
    var date = new Date();
    var myDate = date.toLocaleString(); //获取当前日期
    let userInfo = this.data.userInfo;
    let step = userInfo.step; // 微信步数
    let feedTimes = userInfo.feedTimes; // 总遛狗次数
    let totalStep = userInfo.totalStep; // 总遛狗距离
    let stepRemain = 0; // 剩余步数
    let runStep = 0; // 遛狗距离
    if (step < 0 || step == 0) {
      wx.showToast({
        title: '步数不足',
      });
      return;
    }
    if (step > 0 && step < 2000) {
      runStep = step;
      stepRemain = 0;
      totalStep = totalStep + step;
      feedTimes = feedTimes + 1;
    }
    if (step == 2000 || step > 2000) {
      runStep = 2000;
      stepRemain = step - 2000;
      totalStep = totalStep + 2000;
      feedTimes = feedTimes + 1;
    }
    var runStepInfo = {
      userid: wx.getStorageSync('openid'), // 遛狗的用户id
      userName: this.data.userInfo.nickName, // 遛狗的用户名
      uAvatar: this.data.userInfo.avatarUrl, // 遛狗的头像
      petid: this.data.petId, // 宠物id
      petName: this.data.pet.petName, // 宠物名    因为无法关联查询 所以提前保存宠物名  弊端是如果用户更改宠物名 记录不变  但是为了减少数据库请求次数只好这样
      feedVal: runStep, // 宠物从该用户获得的运动总值
      petUserid: this.data.petUserInfo._openid, // 被遛的狗的主人id
      petUserName: this.data.petUserInfo.nickName, // 被遛的狗的主人昵称
      avatar: this.data.pet.avatar, // 宠物头像
      createTime: myDate, // 创建日期
      updateTime: myDate.substr(0, 10)
    }
    db.collection('p_pet_run').add({
      data: runStepInfo
    }).then(res => {
      // 更新用户信息
      this.updateUserInfo(feedTimes, totalStep, stepRemain);
      // 更新宠物信息
      this.updatePetInfo(runStep);
      // 获取用户信息
      this.getUserInfo();
    })
  },

  // 更新用户信息
  updateUserInfo(feedTimes, totalStep, stepRemain) {
    console.log(this.data.userInfo._id);
    db.collection('p_user').doc(this.data.userInfo._id).update({
      data: {
        feedTimes: feedTimes,
        totalStep: totalStep,
        step: stepRemain
      }
    }).then(res => {
      console.log(res)
    })
  },
  // 更新宠物信息
  updatePetInfo(runStep) {
    let info = this.data.pet;
    let totalEnergy = info.totalEnergy + runStep;
    db.collection('p_pets').doc(this.data.petId).update({
      data: {
        totalEnergy: totalEnergy,
        levelNo: this.petLevel(totalEnergy)
      }
    }).then(res => {
      this.loadPetDet();
    })
  },
  /**
   * 宠物等级
   */
  petLevel(totalEnergy) {
    let petLevelNo = this.data.pet.levelNo;
    let levelNo = 0;
    if (levelNo != 0) {
      return levelNo = parseInt(totalEnergy / (10000 * petLevelNo));
    } else {
      return levelNo = parseInt(totalEnergy / 10000);
    }

  }
})